﻿function splogger(logurl) {
    var uid;
    
    function postData(url, additional) {
        var r = new XMLHttpRequest();
        r.open('POST', logurl, true);
        r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        r.send('title=' + encodeURIComponent(document.title) + '&url=' + url + '&user=' + uid + '&addInfo=' + encodeURIComponent(additional));
    };

    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    this.send = function () {
        if (!SP.ClientContext) {
            setTimeout(this.send, 100);
            return;
        }

        var ctx = new SP.ClientContext.get_current();
        var website = ctx.get_web();
        var currentUser = website.get_currentUser();
        ctx.load(currentUser);
        ctx.executeQueryAsync(function () {
            uid = currentUser.get_email();
            postData(encodeURIComponent(location.href), '');
        },
        function () {
            uid = '';
            postData(encodeURIComponent(location.href), '');
        });
    }

    if (!this.originalNavigate) {
        var self = this;
        self.originalNavigate = Nav.navigate;
        Nav.navigate = function (a) {
            var rootFolder = getUrlVars()["RootFolder"] || "";
            postData(a, rootFolder + '&r=n');
            self.originalNavigate(a);
        };

        (function (open) {
            XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
                open.call(this, method, url, async, user, pass);
                try {
                    if (url.indexOf(window.location.hostname) >= 0 && url.indexOf('client.svc/ProcessQuery') < 0 && url.indexOf('/commandui.ashx') < 0) {
                        var addInfo = '';
                        if (g_currentControl && g_currentControl.files) {
                            for (var i = 0; i < g_currentControl.files.length; i++) {
                                addInfo = addInfo + "f" + i.toString() + "=" + g_currentControl.files[i].fileName + '&';
                            }
                        }
                        var rootFolder = getUrlVars()["RootFolder"] || "";
                        postData(url, addInfo + "rootFolder=" + rootFolder + "&r=a");
                    }
                } catch (ex) {
                }
            };
        })(XMLHttpRequest.prototype.open);
    }
    setTimeout(this.send, 0);
}